home *** CD-ROM | disk | FTP | other *** search
- {*********************************************************}
- {* AASelect *}
- {* Copyright (c) Julian M Bucknall 1998,1999 *}
- {* All rights reserved. *}
- {*********************************************************}
- {* Random selection from an array / shuffling *}
- {* Version 2 *}
- {*********************************************************}
-
- {Note: this unit is released as freeware. In other words, you are free
- to use this unit in your own applications, however I retain all
- copyright to the code. JMB}
-
- unit AASelect;
-
- interface
-
- procedure Shuffle(var aArray; aItemCount : integer; aItemSize : integer);
- {-Random shuffle aItemCount items of size aItemSize in array aArray}
-
- implementation
-
- uses
- SysUtils;
-
- procedure Shuffle(var aArray; aItemCount : integer; aItemSize : integer);
- var
- Inx : integer;
- RandInx : integer;
- SwapItem : PByteArray;
- A : TByteArray absolute aArray;
- begin
- {if the number of items is 0 or 1, there's nothing to do: a shuffle
- would reproduce the status quo}
- if (aItemCount > 1) then begin
- {get an item off the heap so that we can swap items in the array}
- GetMem(SwapItem, aItemSize);
- try
- {for each element, counting from the right..,.}
- for Inx := (aItemCount - 1) downto 1 do begin
- {generate a random number from 0 to the index of the element
- we've currently at}
- RandInx := Random(Inx+1);
- {if the random index does not equal our index, swap the items}
- if (RandInx <> Inx) then begin
- Move(A[Inx*aItemSize], SwapItem^, aItemSize);
- Move(A[RandInx*aItemSize], A[Inx*aItemSize], aItemSize);
- Move(SwapItem^, A[RandInx*aItemSize], aItemSize);
- end;
- end;
- finally
- {free the swap item}
- FreeMem(SwapItem, aItemSize);
- end;
- end;
- end;
-
-
- end.
-